<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>共享出行 - 个人资料</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .header {
            background-color: #007bff;
            color: white;
            padding: 0 20px;
            height: 50px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            margin: 0;
            font-size: 1.2rem;
        }
        .button {
            padding: 0.75rem 1.5rem;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        .button:hover {
            background-color: #0056b3;
            transform: translateY(-2px);
        }
        .button.outline {
            background-color: transparent;
            border: 2px solid white;
        }
        .button.outline:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }
        .main-content {
            padding: 2rem;
            max-width: 800px;
            margin: 0 auto;
            display: flex;
            flex-wrap: wrap;
            gap: 2rem;
        }
        .profile-card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            padding: 2rem;
            flex: 1 1 300px;
        }
        .form-group {
            margin-bottom: 1.5rem;
        }
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #666;
            font-weight: 500;
        }
        .form-group input, .form-group textarea {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
            box-sizing: border-box;
        }
        .form-group input:focus, .form-group textarea:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
        }
        .error-message {
            color: #dc3545;
            font-size: 0.875rem;
            margin-top: 0.5rem;
            display: none;
        }
        .toast {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 1rem 2rem;
            background-color: #28a745;
            color: white;
            border-radius: 4px;
            opacity: 0;
            transition: opacity 0.3s;
            z-index: 1000;
        }
        .toast.show {
            opacity: 1;
        }
        .toast.error {
            background-color: #dc3545;
        }
        .avatar-section {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-bottom: 2rem;
        }
        .avatar-container {
            width: 150px;
            height: 150px;
            border-radius: 50%;
            overflow: hidden;
            margin-bottom: 1rem;
            border: 3px solid #007bff;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            position: relative;
        }
        .avatar-container img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .avatar-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            color: white;
            display: flex;
            justify-content: center;
            align-items: center;
            opacity: 0;
            transition: opacity 0.3s;
            cursor: pointer;
        }
        .avatar-container:hover .avatar-overlay {
            opacity: 1;
        }
        .tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 1.5rem;
        }
        .tab {
            padding: 0.75rem 1.5rem;
            cursor: pointer;
            border-bottom: 3px solid transparent;
            transition: all 0.3s;
        }
        .tab.active {
            border-bottom-color: #007bff;
            color: #007bff;
            font-weight: 500;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
            margin-top: 1.5rem;
        }
        .button.secondary {
            background-color: #6c757d;
        }
        .button.secondary:hover {
            background-color: #5a6268;
        }
        .nav-buttons {
            display: flex;
            gap: 10px;
        }
        .nav-button {
            background: transparent;
            border: 1px solid rgba(255, 255, 255, 0.5);
            border-radius: 4px;
            color: white;
            padding: 6px 12px;
            cursor: pointer;
            transition: background-color 0.2s;
            font-size: 14px;
        }
        .nav-button:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }
        .username {
            margin-right: 15px;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>共享出行系统</h1>
        <div class="nav-buttons">
            <span class="username" id="usernameDisplay"></span>
            <button class="nav-button" onclick="window.location.href='vehicle-list.html'">车辆租赁</button>
            <button class="nav-button" onclick="window.location.href='trip.html'">当前行程</button>
            <button class="nav-button" onclick="window.location.href='trip-history.html'">行程历史</button>
            <button class="nav-button" onclick="window.location.href='payment.html'">支付中心</button>
            <button class="nav-button" onclick="logout()">退出登录</button>
        </div>
    </div>

    <div class="main-content">
        <div class="profile-card">
            <div class="avatar-section">
                <div class="avatar-container">
                    <img id="avatarImage" src="https://via.placeholder.com/150" alt="用户头像">
                    <div class="avatar-overlay" onclick="document.getElementById('avatarUpload').click()">
                        <span>更换头像</span>
                    </div>
                    <input type="file" id="avatarUpload" style="display: none;" accept="image/*" onchange="previewAvatar(event)">
                </div>
                <h3 id="profileUsername">加载中...</h3>
            </div>

            <div class="tabs">
                <div class="tab active" data-tab="basic">基本信息</div>
                <div class="tab" data-tab="password">修改密码</div>
            </div>

            <div id="basicInfoTab" class="tab-content active">
                <form id="profileForm" onsubmit="return updateProfile(event)">
                    <div class="form-group">
                        <label for="username">用户名</label>
                        <input type="text" id="username" name="username" required>
                        <div class="error-message" id="usernameError"></div>
                    </div>
                    <div class="form-group">
                        <label for="phone">手机号</label>
                        <input type="tel" id="phone" name="phone" pattern="[0-9]{11}" required>
                        <div class="error-message" id="phoneError"></div>
                    </div>
                    <div class="form-group">
                        <label for="email">邮箱</label>
                        <input type="email" id="email" name="email" required>
                        <div class="error-message" id="emailError"></div>
                    </div>
                    <div class="form-group">
                        <label for="address">地址</label>
                        <textarea id="address" name="address" rows="3"></textarea>
                    </div>
                    <div class="form-actions">
                        <button type="button" class="button secondary" onclick="window.location.href='profile.html'">取消</button>
                        <button type="submit" class="button">保存修改</button>
                    </div>
                </form>
            </div>

            <div id="passwordTab" class="tab-content">
                <form id="passwordForm" onsubmit="return updatePassword(event)">
                    <div class="form-group">
                        <label for="currentPassword">当前密码</label>
                        <input type="password" id="currentPassword" name="currentPassword" required>
                        <div class="error-message" id="currentPasswordError"></div>
                    </div>
                    <div class="form-group">
                        <label for="newPassword">新密码</label>
                        <input type="password" id="newPassword" name="newPassword" required>
                        <div class="error-message" id="newPasswordError"></div>
                    </div>
                    <div class="form-group">
                        <label for="confirmPassword">确认新密码</label>
                        <input type="password" id="confirmPassword" name="confirmPassword" required>
                        <div class="error-message" id="confirmPasswordError"></div>
                    </div>
                    <div class="form-actions">
                        <button type="button" class="button secondary" onclick="window.location.href='profile.html'">取消</button>
                        <button type="submit" class="button">更新密码</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div id="toast" class="toast"></div>

    <script>
        // 切换标签页
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', function() {
                // 移除所有标签页的active类
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
                
                // 为当前点击的标签页添加active类
                this.classList.add('active');
                const tabId = this.getAttribute('data-tab');
                document.getElementById(tabId + 'InfoTab') ? 
                    document.getElementById(tabId + 'InfoTab').classList.add('active') : 
                    document.getElementById(tabId + 'Tab').classList.add('active');
            });
        });

        // 检查登录状态
        async function checkLogin() {
            try {
                showLoading();
                const response = await fetch('api/check-login', {
                    credentials: 'include'
                });
                const result = await response.json();
                hideLoading();
                
                if (!result.success) {
                    window.location.href = 'login.html';
                    return false;
                }
                
                // 显示用户名
                document.getElementById('usernameDisplay').textContent = result.data.username;
                
                // 加载用户资料
                loadUserProfile();
                
                return true;
            } catch (error) {
                hideLoading();
                console.error('检查登录状态失败:', error);
                window.location.href = 'login.html';
                return false;
            }
        }

        // 退出登录
        async function logout() {
            try {
                showLoading();
                const response = await fetch('api/logout', {
                    method: 'POST',
                    credentials: 'include'
                });
                const result = await response.json();
                
                hideLoading();
                if (result.success) {
                    window.location.href = 'login.html';
                }
            } catch (error) {
                hideLoading();
                console.error('退出登录失败:', error);
            }
        }

        // 加载用户资料
        async function loadUserProfile() {
            try {
                const response = await fetch('api/user/profile', { credentials: 'include' });
                const result = await response.json();
                
                if (result.success) {
                    const user = result.data;
                    document.getElementById('username').value = user.username || '';
                    document.getElementById('phone').value = user.phone || '';
                    document.getElementById('email').value = user.email || '';
                    document.getElementById('address').value = user.address || '';
                    document.getElementById('profileUsername').textContent = user.username || '';
                    
                    // 加载头像
                    if (user.avatarUrl) {
                        document.getElementById('avatarImage').src = user.avatarUrl;
                    }
                } else {
                    showToast(result.message, true);
                }
            } catch (error) {
                console.error('加载用户资料失败:', error);
                showToast('加载用户资料失败，请稍后重试', true);
            }
        }

        // 预览头像
        function previewAvatar(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('avatarImage').src = e.target.result;
                };
                reader.readAsDataURL(file);
            }
        }

        // 更新用户资料
        async function updateProfile(event) {
            event.preventDefault();
            
            // 重置错误信息
            document.querySelectorAll('.error-message').forEach(el => {
                el.style.display = 'none';
                el.textContent = '';
            });

            // 获取表单数据
            const username = document.getElementById('username').value.trim();
            const phone = document.getElementById('phone').value.trim();
            const email = document.getElementById('email').value.trim();
            const address = document.getElementById('address').value.trim();

            // 验证表单数据
            let hasError = false;
            
            if (!username) {
                showError('usernameError', '用户名不能为空');
                hasError = true;
            }
            
            if (!phone) {
                showError('phoneError', '手机号不能为空');
                hasError = true;
            } else if (!phone.match(/^[0-9]{11}$/)) {
                showError('phoneError', '请输入有效的11位手机号');
                hasError = true;
            }
            
            if (!email) {
                showError('emailError', '邮箱不能为空');
                hasError = true;
            } else if (!isValidEmail(email)) {
                showError('emailError', '请输入有效的邮箱地址');
                hasError = true;
            }

            if (hasError) return false;

            // 准备表单数据
            const formData = {
                username,
                phone,
                email,
                address
            };

            // 上传头像
            const avatarInput = document.getElementById('avatarUpload');
            if (avatarInput.files && avatarInput.files[0]) {
                const avatarFormData = new FormData();
                avatarFormData.append('avatar', avatarInput.files[0]);
                
                try {
                    const uploadResponse = await fetch('api/user/upload-avatar', {
                        method: 'POST',
                        body: avatarFormData,
                        credentials: 'include'
                    });
                    
                    const uploadResult = await uploadResponse.json();
                    if (uploadResult.success) {
                        formData.avatarUrl = uploadResult.data.avatarUrl;
                    }
                } catch (error) {
                    console.error('上传头像失败:', error);
                }
            }

            try {
                const response = await fetch('api/user/profile', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData),
                    credentials: 'include'
                });

                const result = await response.json();

                if (result.success) {
                    showToast('个人资料更新成功');
                    setTimeout(() => {
                        window.location.href = 'profile.html';
                    }, 1500);
                } else {
                    showToast(result.message, true);
                }
            } catch (error) {
                console.error('更新个人资料失败:', error);
                showToast('更新失败，请稍后重试', true);
            }

            return false;
        }

        // 更新密码
        async function updatePassword(event) {
            event.preventDefault();

            // 重置错误信息
            document.querySelectorAll('.error-message').forEach(el => {
                el.style.display = 'none';
                el.textContent = '';
            });

            // 获取表单数据
            const currentPassword = document.getElementById('currentPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;

            // 验证表单数据
            let hasError = false;
            
            if (!currentPassword) {
                showError('currentPasswordError', '当前密码不能为空');
                hasError = true;
            }
            
            if (!newPassword) {
                showError('newPasswordError', '新密码不能为空');
                hasError = true;
            } else if (newPassword.length < 6) {
                showError('newPasswordError', '密码长度不能少于6位');
                hasError = true;
            }
            
            if (newPassword !== confirmPassword) {
                showError('confirmPasswordError', '两次输入的密码不一致');
                hasError = true;
            }

            if (hasError) return false;

            try {
                const response = await fetch('api/user/update', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        currentPassword,
                        newPassword
                    }),
                    credentials: 'include'
                });

                const result = await response.json();

                if (result.success) {
                    showToast('密码更新成功，请重新登录');
                    setTimeout(() => {
                        window.location.href = 'login.html';
                    }, 1500);
                } else {
                    if (result.message.includes('当前密码')) {
                        showError('currentPasswordError', result.message);
                    } else {
                        showToast(result.message, true);
                    }
                }
            } catch (error) {
                console.error('更新密码失败:', error);
                showToast('更新失败，请稍后重试', true);
            }

            return false;
        }

        // 显示错误信息
        function showError(elementId, message) {
            const element = document.getElementById(elementId);
            element.textContent = message;
            element.style.display = 'block';
        }

        // 验证邮箱
        function isValidEmail(email) {
            const re = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
            return re.test(email);
        }

        // 显示提示信息
        function showToast(message, isError = false) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.className = `toast${isError ? ' error' : ''}`;
            toast.classList.add('show');
            
            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }

        // 页面加载时执行
        window.onload = checkLogin;
    </script>
</body>
</html> 